<template>
	<view scroll-y class='bluetooth-device-list'>
		<custom-header-bar title="添加设备" bg="1" backStatus="1"></custom-header-bar>
		<div class="search-state">
			<u-icon v-if="SearchState===true" labelPos="left" label="正在搜索" name="more-dot-fill"></u-icon>
			<u-icon v-else @click="initBle" label="重新搜索" name="reload"></u-icon>
		</div>
		<div class="content-box">
			<div v-if="BlueAvailable===false">
				<empty-loading type="loading" text="等待您打开本机蓝牙设备"></empty-loading>
			</div>
			<div v-else-if="BlueDevice===''">
				<empty-loading type="loading" text="正在检索蓝牙设备"></empty-loading>
			</div>
			<div v-else-if="BlueDevice.length===0">
				<empty-loading type="empty" text="暂无蓝牙设备"></empty-loading>
			</div>
			<div class="device-list" v-else>
				<div class="item" v-for="(item,index) in BlueDevice" @click="createBLEConnection(item)">
					<div class="text">
						<div>{{item.nickName||item.name}}</div>
						<div>{{item.deviceId}}</div>
					</div>
					<image class="icon" v-if="item.state==='no'" src="/static/icon-bluetooth-gray.png"></image>
					<u-loading-icon v-if="item.state==='ing'" size="36"></u-loading-icon>
					<image v-if="item.state==='link'" class="icon" src="/static/icon-bluetooth-blue.png"></image>
				</div>
			</div>
		</div>
		<u-popup round="18" :show="tipshow" mode="center">
			<view class="popup-model-wrapper">
				<div class="title">
					<image class="image" src="/static/icon-success.png"></image>
					<div class="text">设备绑定成功</div>
				</div>
				<div class="content">
					<input class="input" type="text" maxlength="10" v-model="deviceName" placeholder="请为您的设备命名" />
				</div>
				<div class="operate-wrapper">
					<button border="bottom" class="button confirm" @click="popupConfirm">确定</button>
				</div>
			</view>
		</u-popup>
	</view>
</template>

<script>
	const ServerUUID = '6E400001-B5A3-F393-E0A9-E50E24DCCA9E'
	const CharacteristicsNotify = '6E400003-B5A3-F393-E0A9-E50E24DCCA9E'
	const CharacteristicsWrite = '6E400002-B5A3-F393-E0A9-E50E24DCCA9E'
	import {
		mapMutations,
		mapGetters,
		mapActions
	} from 'vuex'
	import {
		InitBlueTooth,
		CreateBlueToothConnection,
		ReadBlueTooth
	} from "@/utils/BLE.js"
	import {
		AddDevice
	} from "@/api/device.js"
	import CustomHeaderBar from "@/components/custom-header-bar.vue"
	import EmptyLoading from "@/components/empty-loading.vue"
	import storage from "@/utils/storage.js"
	export default {
		components: {
			CustomHeaderBar,
			EmptyLoading
		},
		data() {
			return {
				tipshow: false,
				result: [],
				deviceName: "",
			}
		},
		computed: {
			...mapGetters(['BlueDevice', 'BlueAvailable', 'SearchState', 'CurrentLinkDevice'])
		},
		onLoad() {},
		onShow() {
			// this.initBle()
		},
		methods: {
			...mapMutations(['SetCurrentLinkDevice']),
			...mapActions(['WriteBlueTooth','SearchAndGetBlueToothList', 'ActionBuleList', 'SetupCurrentDeviceState',
				'ActionBlueBodyInfo'
			]),
			// 初始化蓝牙
			initBle() {
				InitBlueTooth(true).then((resinit) => {
					// 开始搜索蓝⽛设备
					this.SearchAndGetBlueToothList()
				})
			},
			// 创建蓝牙连接，连接蓝牙
			createBLEConnection(item) {
				if (item.state === 'link' || item.state === 'ing') return
				let that = this
				that.SetupCurrentDeviceState({
					...item,
					state: 'ing'
				}, that)
				console.log("创建连接----蓝牙页面")
				CreateBlueToothConnection(item).then((res) => {
					console.log('连接的设备：', res)
					// -------设置当前设备---------
					that.currentDivice = {
						deviceId: res.device.deviceId,
						name: res.device.name,
						serviceId: res.service.uuid,
						characteristicId: res.c.uuid,
						state: 'link'
					}
					// ----------------
					if (!item.nickName) {
						that.tipshow = true
					} else {
						setTimeout(() => {
							this.WriteBlueTooth('baseinfo')
							// 同步时间
							// WriteBlueTooth('time')
							// 获取设备电量
							this.WriteBlueTooth('electric')
							// 一件测量
							// this.WriteBlueTooth('test')
							// 同步数据
							this.WriteBlueTooth('tongbu')
						}, 3000)
						uni.navigateBack()
					}
					that.SetupCurrentDeviceState(that.currentDivice, that)
					ReadBlueTooth(res.device, res.service, res.c)
				}, (res) => {
					uni.showToast({
						title: "无法连接当前设备",
						icon: "none"
					})
					that.result.push(JSON.stringify(res))
					that.SetupCurrentDeviceState({
						...item,
						state: 'no'
					}, that)
				})
			},
			popupConfirm() {
				let that = this
				if (that.deviceName === '') {
					uni.showToast({
						title: "请为您的设备命名",
						icon: "none"
					})
					return
				}
				AddDevice({
					...that.currentDivice,
					nickName: that.deviceName
				}).then((res) => {
					console.log('AddDevice', res)
					if (res.data.code === 500) {
						uni.showToast({
							title: res.data.msg,
							icon: "none"
						})
						that.tipshow = false
						that.SetupCurrentDeviceState('')
						return
					}
					that.tipshow = false
					that.SetupCurrentDeviceState({
						...this.currentDivice,
						nickName: this.deviceName
					})
					setTimeout(() => {
						this.WriteBlueTooth('baseinfo')
						// 同步时间
						this.WriteBlueTooth('time')
						// 获取设备电量
						this.WriteBlueTooth('electric')
						// 一件测量
						// this.WriteBlueTooth('test')
						// 同步数据
						this.WriteBlueTooth('tongbu')
					}, 3000)
					uni.navigateBack()
				})
			}
		}
	}
</script>

<style lang="scss">
	.bluetooth-device-list {
		min-height: 100vh;
		padding-top: 160upx;
		box-sizing: border-box;
		background-color: #F4f4f4;

		.search-state {
			padding: 32upx;
			display: flex;
			justify-content: flex-end;
		}

		.content-box {
			padding: 24upx;
		}

		.device-list {
			padding: 24upx;
			background-color: #ffffff;
			border-radius: 30upx;

			.item {
				padding: 30upx 0;
				border-bottom: 2upx solid #F2f2f2;
				color: #484848FF;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.icon {
					width: 40upx;
					height: 40upx;
				}

				&:last-child {
					border: none;
				}
			}

			&:last-child {
				border: none;
			}
		}

		.popup-model-wrapper {
			width: 420upx;
			border-radius: 30upx;
			padding: 40upx;
			box-sizing: border-box;

			.title {
				display: flex;
				justify-content: center;
				align-items: center;

				.image {
					margin-right: 24upx;
					width: 52upx;
					height: 52upx;
				}

				.text {
					font-size: 34upx;
					color: #000000CC;
				}
			}

			.content {
				margin-top: 50upx;
				color: #666666FF;
				font-size: 26upx;
				padding: 12upx 0;
				border-bottom: 2upx solid #f4f4f4;

				.input {
					font-size: 26upx;
				}
			}

			.operate-wrapper {
				margin-top: 56upx;
				display: flex;
				justify-content: space-around;

				.button {
					width: 320upx;
					height: 60upx;
					line-height: 60upx;
					font-size: 28upx;
					border-radius: 4upx
				}

				.del {
					background: #EBEDF0FF;
					color: #BFBEBEFF;
				}

				.confirm {
					background: #61D7CAFF;
					color: #FFFFFFFF;
				}
			}
		}
	}
</style>
